package com.school.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.Logger;

/**
 * @author gaobiao
 * 
 */
public class FileUtils {
	private static Logger logger = Logger.getLogger(FileUtils.class);

	public static void saveFile(File file, String fileName) throws IOException {
		InputStream in = new FileInputStream(file);
		fileName = getRealPath(fileName);
		File file1 = new File(fileName);
		// 创建文件目录
		File dir = file1.getParentFile();
		if (dir != null && !dir.exists()) {
			dir.mkdirs();
		}
		// 判断文件是否存在，存在则先删除
		if (file1.exists()) {
			file1.delete();
		}
		OutputStream out = new FileOutputStream(fileName);
		byte[] buffer = new byte[1024 * 1024];
		int length;
		while ((length = in.read(buffer)) > 0) {
			out.write(buffer, 0, length);
		}
		in.close();
		out.close();
	}

	/**
	 * 得到文件或者路径的 相对于操作系统的 真实路径
	 * 
	 * @param s
	 * @return
	 */
	public static String getRealPath(String s) {

		try {
			String separator = File.separator;
			if ("/".equalsIgnoreCase(separator)) {
				s = s.replace('\\', '/');
			} else {
				s = s.replace('/', '\\');
			}
		} catch (Exception e) {
			logger.error("错误。" + e.getMessage());
		}
		return s;
	}
}
